import dayjs from "dayjs";

//防抖
export function debounce(callback: Function) {
  let timer: NodeJS.Timeout | null = null;
  return function () {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(() => {
      callback();
      timer = null;
    }, 500);
  };
}

//节流
export function throttle(callback: Function, del: number) {
  let timer: NodeJS.Timeout | null = null;
  return function () {
    if (timer) return;
    timer = setTimeout(() => {
      callback();
      timer = null;
    }, del);
  };
}

//处理时间
export function formattime(s: string): string {
  return dayjs(s).format("YYYY-MM-DD HH:mm:ss");
}

//滚动动画
export function scrollanimate(ele: Element, top: number, step: number) {
  const di = () => {
    ele.scrollTo(0, ele.scrollTop + step);
    if (ele.scrollTop < top) {
      requestAnimationFrame(di);
    }
  };
  requestAnimationFrame(di);
}

export function getElementTop(el:any, targetEl:any):number {
  const parent = el.offsetParent;
  const top = el.offsetTop;
  return parent && parent !== targetEl
    ? getElementTop(parent, targetEl) + top
    : top;
}
